package org.gl.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.gl.GlobalVariable;

public class DownLoadFile_HTTP {
	// final static String url =
	// "http://192.168.1.21/3.php?page=/opt/Resource_one/Resource_36/oh.mp4";
	DownLoadListener mListener;
	InputStream is = null;
	long size = 0;
	private boolean isBeForce;

	public void setResouceDownloadListener(
			DownLoadListener mResouceDownloadListener) {
		this.mListener = mResouceDownloadListener;
	}

	/**
	 * post鏂规硶涓嬭浇涓�釜鏂囦欢 url:
	 * name=yangweidi&password=e10adc3949ba59abbe56e057f20f883e&id=0
	 * 
	 * @param strUrl
	 * @param fileSavePathName
	 * @param params
	 *            params.add(new
	 *            BasicNameValuePair("name","this is post"));UTF-8
	 * @return if fail return null else filePath
	 */
	public String downLoadByHttpPost(String strUrl, String fileSavePathName,
			List<BasicNameValuePair> params) {
		if (strUrl == null) {
			System.err.println("Url  is null");
			strUrl = "http://192.168.1.21/JsScript/JsSrcCenter/SrcDown.php";
		}
		if (fileSavePathName == null) {
			fileSavePathName = "/home/zyfgeliang/videoRes/oh.mp4";
			System.err.println("file  is null");
		}

		try {
			File file = null;
			file = (new FileUtil()).checkFile(fileSavePathName, true);
			if (file == null) {
				return null;
			}
			DefaultHttpClient client = GlobalVariable.DefaultHttpClient;
			HttpPost httpPost = new HttpPost(strUrl);
			if (params != null) {
				httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			}
			for (BasicNameValuePair basicNameValuePair : params) {
				if ("size".equals(basicNameValuePair.getName())) {
					try {
						size = Long.parseLong(basicNameValuePair.getValue());
					} catch (Exception e) {
						e.printStackTrace();
						size = 0;
					}
				}
				;
			}
			String fileAbsolutePath = file.getAbsolutePath();
			sendStartDownloadMeasage(fileAbsolutePath);
			if (file.exists() && file.length() == size) {
				sendComDownloadMeasage(fileAbsolutePath);
				System.out.println("file has exists");
				return fileAbsolutePath;
			}
			HttpResponse mHttpResponse = client.execute(httpPost);
			int errcode = mHttpResponse.getStatusLine().getStatusCode();
			if (errcode == 200) {
				isBeForce = false;
				is = mHttpResponse.getEntity().getContent();
				return writeFile(file, is);
			} else {
				throw new IOException("fail,servers errcode:" + errcode);
			}
		} catch (IllegalStateException e) {
			sendFailDownloadMeasage(e.getMessage(), 0);
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			sendFailDownloadMeasage(e.getMessage(), 0);
			e.printStackTrace();
		} catch (IOException e) {
			sendFailDownloadMeasage(e.getMessage(), 0);
			System.err.println("error open url:" + strUrl);
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	public void sendStartDownloadMeasage(String fileAbsolutePath) {
		if (mListener != null) {
			mListener.downloadStart(fileAbsolutePath, 0, size);
		}
	}

	public void sendDoingDownloadMeasage(String fileAbsolutePath,
			long progerss, long totalProgeress) {
		if (mListener != null) {
			mListener.downloading(fileAbsolutePath, progerss, size, 0);
		}
	}

	public void sendComDownloadMeasage(String fileAbsolutePath) {
		if (mListener != null) {
			mListener.downloadcompled(fileAbsolutePath, 0);
		}
	}

	public void sendFailDownloadMeasage(String fileAbsolutePath, int errcode) {
		if (mListener != null) {
			mListener.downloaderr(fileAbsolutePath, 0, errcode);
		}
	}

	/**
	 * 鍐欏叆鏂囦欢
	 * 
	 * @param file
	 * @param is
	 * @return file.getAbsolutePath();
	 * @throws IOException
	 */
	public String writeFile(File file, InputStream is) throws IOException {
		if (file == null) {
			return null;
		}
		if (is == null) {
			return null;
		}
		FileOutputStream fos = null;
		String fileName = file.getAbsolutePath();
		try {
			long fileCousor = 0;
			fos = new FileOutputStream(file);
			byte bytes[] = new byte[1024 * 4];
			int x;
			while ((x = is.read(bytes)) != -1 ) {
				if (isBeForce) {
					sendFailDownloadMeasage("download has been stop", 0);
					break;
				}
				fos.write(bytes, 0, x);
				fileCousor += x;
				// if (fileCousor>size) {
				// throw new IOException("fileCousorsize > size");
				// }else{
				// Loger.info(0, ""+fileCousor);//FIXME 杩涘害鏄剧ず鍑嗙‘
				sendDoingDownloadMeasage(fileName, fileCousor, size);
				// }
			}

		} finally {
			is.close();
			fos.flush();
			fos.close();
		}
		sendComDownloadMeasage(fileName);
		return file.getAbsolutePath();
	}

	/**
	 * 鎵撳紑涓�釜URL涓嬭浇鏂囦欢
	 * 
	 * @param strUrl
	 * @param fileSavePathName
	 * @return if fail return null else filePath
	 */
	public String downLoadByURL(String strUrl, String fileSavePathName) {

		if (strUrl == null) {
			System.err.println("Url  is null");
			strUrl = "http://192.168.1.21/3.php?page=/opt/Resource_one/Resource_36/oh.mp4";
		}
		if (fileSavePathName == null) {
			fileSavePathName = "/home/zyfgeliang/videoRes/oh.mp4";
			System.err.println("file  is null");
		}
		InputStream is = null;

		try {
			File file = null;
			file = (new FileUtil()).checkFile(fileSavePathName, true);
			if (file == null) {
				return null;
			}
			URL url = new URL(strUrl);
			is = url.openStream();
			return writeFile(file, is);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("error open url:" + strUrl);
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	public void stopForceDownloadFile() {
		if (is != null) {
			isBeForce = true;
		}
	}

}